#include "bsp_uart1.h"
#include "wb32l003.h"

/**
  * @name   uart1_init
  * @brief  Initializes the UART1 peripheral.
  * @param  apbclk: Specifies the clock frequency of the APB where the UART resides.
  * @param  baud: Specifies the baud rate for communication.
  * @retval None
  */
void uart1_init(uint32_t apbclk, uint32_t baud)
{
  uint32_t tmp;

  /* Enable GPIOD and UART1 clock */
  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOD, ENABLE);
  RCC_APBPeriphClockCmd(RCC_APBPeriph_UART1, ENABLE);

  /* Reset UART1 */
  RCC_APBPeriphResetCmd(RCC_APBPeriph_UART1, ENABLE);
  RCC_APBPeriphResetCmd(RCC_APBPeriph_UART1, DISABLE);

  /*
    PD5 UART1_TX
    PD6 UART1_RX
   */
  GPIO_Init(GPIOD, GPIO_Pin_5 | GPIO_Pin_6, GPIO_PUPD_NOPULL | GPIO_OTYPE_PP | GPIO_SPEED_HIGH | GPIO_AF7);

  /* Configure UART1 */
  tmp = UART1->SCON;
  tmp |= (UART_SCON_DBAUD | (0x01 << 6) | UART_SCON_REN);
  UART1->SCON = tmp;

  tmp = UART1->BAUDCR;
  tmp = ((((2 * apbclk) / (32 * baud) - 1) & 0xFFFF) | (0x01 << 16));
  UART1->BAUDCR = tmp;

  tmp = UART1->SCON;
  tmp |= (UART_SCON_TIEN | UART_SCON_RIEN);
  UART1->SCON = tmp;
}

/**
  * @name   uart1_send
  * @brief  Send data through UART1
  * @param  buffer: Specifies a buffer pointer to the data to be sent.
  * @param  length: Specifies the length of the data to send.
  * @retval None
  */
void uart1_send(const uint8_t* buffer, uint32_t length)
{
  while (length)
  {
    UART1->SBUF = *buffer;
    while (!(UART1->INTSR & UART_INTSR_TI))
      ;
    UART1->INTCLR |= UART_INTCLR_TICLR_Msk;
    buffer++;
    length--;
  }
}
